import re
import requests

import aliyun_ddns
import ding_webhook
from pathlib import Path

# 设置代理
PROXIES = {
    "http": "http://127.0.0.1:7890",
    "https": "http://127.0.0.1:7890"
}

# 群机器人access_token
ACCESS_TOKEN = "xxxxxxxxxxxxxx"
# 密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符串
SECRET = 'xxxxxxxxxxxx'

# DDNS相关参数
API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
API_SECRET = 'xxxxxxxxxxxx'
DOMAIN = 'xxxxxxxxx'

ip_get_api = ['https://searchplugin.csdn.net/api/v1/ip/get',
              'https://www.ip.cn/api/index?ip&type=0',
              'https://www.taobao.com/help/getip.php',
              'https://pv.sohu.com/cityjson']


def GetCurrentIP():
    for api_url in ip_get_api:
        try:
            print(f'Try API: {api_url}')
            input_string = requests.get(api_url).text.strip()
            ip_pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
            match = re.search(ip_pattern, input_string)
            if match:
                return match.group(0)
        except Exception as e:
            print(f"Error fetching IP from {api_url}: {e}")
    return None


def ReadFile(path):
    file = None
    content = None
    try:
        file = open(path, 'r')
    except Exception as e:
        print(f"Caught an exception: {e}")
    else:
        content = file.read()
    finally:
        if file:
            file.close()
    return content


def WriteFile(path, content):
    file = None
    try:
        file = open(path, 'w')
    except Exception as e:
        print(f"Caught an exception: {e}")
    else:
        file.write(content)
    finally:
        if file:
            file.close()


# 使用示例
if __name__ == "__main__":
    # 创建DingTalkAlarm实例
    dingtalk_alarm = ding_webhook.DingTalkAlarm(ACCESS_TOKEN, SECRET)

    # 创建 DDNSUpdater 实例
    ddns_updater = aliyun_ddns.AliyunDNSUpdater(
        api_key=API_KEY,
        api_secret=API_SECRET,
        domain=DOMAIN
    )
    response = ddns_updater.request_records()

    # 解析 statusCode 信息
    if not response or response.status_code != 200:
        print("Status Code:", response.status_code)
        dingtalk_alarm.send_alert("RGJZ::DDNS结果",
                                  "<font color=#FF0000>RGJZ::DDNS结果</font>\n\nDNS信息获取失败，status code：{}\n".format(
                                      response.status_code), True)
        exit(0)

    records = []
    rsp_records = response.body.domain_records.record
    for record in rsp_records:
        if record.type == 'A':
            records.append(record)

    # 运行更新
    last_ip_path = Path('last_ip')
    last_ip = ReadFile(last_ip_path)
    current_ip = GetCurrentIP()
    if not current_ip:
        # 调用send_alert传入需要传递的参数发送消息
        dingtalk_alarm.send_alert("RGJZ::DDNS结果", "<font color=#FF0000>RGJZ::DDNS结果</font>\n\n获取IP地址出错！\n",
                                  True)
    elif current_ip == last_ip:
        # 调用send_alert传入需要传递的参数发送消息
        # dingtalk_alarm.send_alert("RGJZ::DDNS结果", "<font color=#0000FF>RGJZ::DDNS结果</font>\n\nIP地址没有发生变化，当前IP：{}\n".format(current_ip), False)
        exit(0)

    ddns_ret = 0
    for record in records:
        print('record_id:', record.record_id)
        print('rr:', record.rr)
        print('type:', record.type)
        print('value:', record.value)
        ret = ddns_updater.ddns(record.record_id, record.rr, record.type, current_ip)
        if not ret or ret.status_code != 200:
            ddns_ret = ddns_ret - 1
    if ddns_ret < 0:
        dingtalk_alarm.send_alert("RGJZ::DDNS结果",
                                  "<font color=#FF0000>RGJZ::DDNS结果</font>\n\nDNS信息更新失败，当前IP：{}\n".format(
                                      current_ip), True)
    else:
        dingtalk_alarm.send_alert("RGJZ::DDNS结果",
                                  "<font color=#00FF00>RGJZ::DDNS结果</font>\n\nDNS信息更新成功，当前IP：{}\n".format(
                                      current_ip), False)
        WriteFile(last_ip_path, current_ip)
